<cfcomponent extends="Model">

	<cffunction name="init">
		
		<cfset beforeCreate("assignPosition")>
		
		<cfset belongsTo(name="Team",modelName="Team", foreignKey="teamID")>
		<cfset belongsTo(name="Player",modelName="Player", foreignKey="playerID")>
		
		<cfset validatesUniquenessOf(properties="teamID,playerID",scope="teamID,playerID",message="You cannot add the same player to the same team")>
	</cffunction>
	
	<cffunction name="assignPosition" hint="Automatically determines their position and adds to the end">

		<!--- See if there is a value yet, if not its just being created, assign it 1 --->
		<cfif Len(this.Position) EQ 0>
			<cfset this.Position = 1>
		</cfif>
		
		<!--- Now we need to find other players in this team and find out what the last position is --->
		<cfset teamPlayerPosition = model("TeamPlayer").maximum(property="Position",where="TeamID=#this.TeamID#")>		
		<cfif Len(teamPlayerPosition)>
			<cfif isNumeric(this.Position)>
				<cfset this.Position = teamPlayerPosition +1>			
			</cfif>
		</cfif>
		
		<cfreturn true>
	</cffunction>
	
	<cffunction name="getScorecard" hint="Grabs the home and away team details for the scorecard">
		<cfargument name="fixtureID" type="numeric" required="true">
		<cfset var loc = {}>
		
		<cfquery name="loc.query" datasource="#variables.wheels.class.connection.datasource#">
			
			
				
				SELECT 
						f.FixtureID,
						f.homeTeamId,
						f.awayTeamId,
						ht.PlayerID as HomeTeamPlayerID,
						--hp.FirstName as HomeTeamPlayerFirstName,
						--hp.LastName as HomeTeamPlayerLastName,
						ht.Position as HomeTeamPlayerPosition,
						at.PlayerID as AwayTeamPlayerID,
						--ap.FirstName as AwayTeamPlayerFirstName,
						--ap.LastName as AwayTeamPlayerLastName,
						at.Position as AwayTeamPlayerPosition
						
				FROM		Fixtures f
				INNER JOIN	TeamPlayers ht ON f.homeTeamId = ht.TeamID
				--INNER JOIN	Players hp ON ht.PlayerID = hp.PlayerID
				INNER JOIN	TeamPlayers at ON f.awayTeamId = at.TeamID
				--INNER JOIN	Players ap ON at.PlayerID = ap.PlayerID
	
				WHERE	f.FixtureID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.fixtureID#">
				ORDER BY ht.Position, at.Position
				
			
		</cfquery>
		
		<cfreturn loc.query>
	</cffunction>
		
</cfcomponent>